<?php
// 接口-出库单接口
namespace interface\pda;

use verify;
use control\supplierClass;
use control\inStockOtherClass;
use control\optionSettingClass;
use control\tempInventoryClass;
use control\machiningOrderClass;
use control\inventoryBalanceClass;
use control\codeTemplateClass;

class outStockClass extends index
{
	private const        page        = 'outStock';
	private const        tableRecord = 'inventory_record';
	private const        title       = '出库单';
	
	public function search()
	{
		$this->code         = 1;
		$this->resp['data'] = [
			'orderNo'     => '单据条码',
			'warehouseId' => find(['table' => 'warehouse', 'field' => 'id as value, name as text', 'where' => " coid = '" . self::$coid . "' AND state = '启用' "])['array'],
			'action'      => [
				'待出库', '已出库',
			],
			'state'       => [
				'待出库', '部分出库', '已出库', '已复核',
			],
		];
	}
	
	
	/**
	 * 列表
	 *
	 * @return void
	 */
	public function list()
	{
		$action = $this->post('action');
		//获取查询结果
		$where = search([
			"="    => [
				'coid' => self::$coid,
			],
			'like' => [
				'orderNo' => $this->post('orderNo'),
			],
			'in'   => $action == '待出库' ? (['state' => $this->post('state') ?: ['待出库', '部分出库']]) : [],
		]);
		$page  = $this->page(["table" => inStockClass::tableMap($action)['table'], "where" => $where, "order" => "time desc"]);
		//数据分析
		$data['result'] = [];
		foreach ($page['array'] as $array) {
			$result           = find([
				'table'  => inStockClass::tableMap($action)['tableMx'],
				'field'  => ' any_value(materialId) as materialId, IFNULL(sum(num), 0) as total ',
				'single' => " orderId = '$array[id]' ",
			]);
			$material         = query('material', " id = '$result[materialId]' ");
			$data['result'][] = [
				'action'     => $action,
				'id'         => $array['id'],
				'orderNo'    => $array['orderNo'],
				'type'       => $array['type'],
				'target'     => $array['targetId'],
				'targetName' => inStockOtherClass::getCompanyName($array['targetId']),
				'material'   => $material['name'] . '等' . static::formattingFigure($result['total']) . $material['unit'],
				"state"      => $array['state'],
				'time'       => self::formatDate($array['time'], 'Y/m/d'),
			];
		}
		$data['page'] = $page['para'];
		//返回
		$this->code         = 1;
		$this->resp['data'] = $data;
	}
	
	/**
	 * 删除
	 *
	 * @return void
	 */
	public function delete(): void
	{
		$array  = $this->post('listId') ?? $this->post('id');
		$action = $this->post('action') ?: '已出库';
		if (!$this->power(self::page, "del")) {
			$this->resp['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$this->resp['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(inStockClass::tableMap($action)['table'], " id = '$id' ");
				if ($info['state'] == '已出库') {
					$warn = "删除失败：已出库，暂不能删除";
				} else {
					//最后删除基本参数
					delete(array("table" => inStockClass::tableMap($action)['table'], "where" => " id = '$id' "));
					delete(array("table" => inStockClass::tableMap($action)['tableMx'], "where" => " orderId = '$id' "));
					delete(array("table" => self::tableRecord, "where" => " changesId = '$id' "));
					delete(array("table" => 'auditing_follow', "where" => " typeId = '$id' "));
					//返回
					$warn = "删除成功";
					$x++;
				}
				$text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$this->resp['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
			$this->code         = 1;
		}
	}
	
	/**
	 * 详情
	 *
	 * @return void
	 */
	public function detail()
	{
		$id     = $this->post('id');
		$action = $this->post('action') ?: '已出库';
		$info   = query(inStockClass::tableMap($action)['table'], "id = '" . $id . "'");
		if (empty($id)) {
			$this->resp['warn'] = "ID为空";
		} elseif (empty($info['id'])) {
			$this->resp['warn'] = "未找到此" . self::title;
		} else {
			$audit      = find([
				'table' => 'auditing_follow',
				'where' => " typeId = '$info[id]'",
			]);
			$result     = find([
				'table' => inStockClass::tableMap($action)['tableMx'],
				'where' => " orderId = '$info[id]' order by time desc",
			]);
			$detail     = $outRecord = [];
			$totalMoney = 0;
			foreach ($result['array'] as $value) {
				$material    = query('material', " id = '$value[materialId]' ");
				$materialSku = query('material_sku', " id = '$value[materialSkuId]' ");
				$warehouse   = query('warehouse', " id = '$value[warehouseId]'");
				$rid         = self::generateId([$value['orderId'], $value['materialSkuId']]);
				$temp        = find(['table' => 'auditing_follow', 'where' => "typeId = '$rid' AND type = '出库单' order by time desc"])['array'];
				$detail[]    = [
					'id'              => $value['id'],
					'materialId'      => $value['materialId'],
					'materialSkuId'   => $value['materialSkuId'],
					'code'            => $material['code'],
					'name'            => $material['name'],
					'model'           => $material['model'],
					'warehouseId'     => $warehouse['id'],
					'warehouse'       => $warehouse['name'],
					'unit'            => $material['unit'],
					'batch'           => $value['batch'],
					'num'             => $value['num'],
					'price'           => $value['price'],
					'mxText'          => $value['text'],
					'materialSkuName' => $materialSku['name'],
					'brand'           => $material['brand'],
					'mtype'           => inventoryListClass::getTypeName($material['typeId']),
					'text'            => $value['text'],
					'orderNum'        => $value['orderNum'],
					'inventoryNum'    => inventoryBalanceClass::inventoryNum($value['materialSkuId'], $warehouse['id']),
					// 可用库存计算
					'usableNum'       => machiningOrderClass::inventory($value['materialSkuId'], $value['unit'], $warehouse['id']),
					'unitArray'       => inventoryBalanceClass::materialUnit($value['id']),
					'total'           => $value['num'] * $value['price'],
				];
				$totalMoney  += $value['num'] * $value['price'];
				if (!self::is_null_array($temp)) {
					$outRecord = array_merge($outRecord, $temp);
				}
			}
			$data['result'] = [
				'info'        => [
					"id"         => $info['id'],
					'staffName'  => self::findStaff($info['stid']),
					'orderNo'    => $info['orderNo'],
					'orderDate'  => V($info, 'recordDate', 'orderDate'),
					'type'       => $info['type'],
					'target'     => $info['targetId'],
					'targetId'   => $info['targetId'],
					'targetName' => inStockOtherClass::getCompanyName($info['targetId']),
					"state"      => $info['state'],
					'text'       => $info['text'],
					'date'       => self::formatDate($info['time'], 'm/d'),
				],
				'detail'      => $detail,
				'outRecord'   => $outRecord ? self::my_sort($outRecord, 'time', SORT_DESC, SORT_STRING) : [],
				'auditRecord' => $audit['array'],
				'total'       => [
					'num'   => count($detail),
					'money' => $totalMoney,
				],
				'check'       => optionSettingClass::getSettingItem('库存', 'checkCtrl'),
			
			];
			//返回
			$this->code         = 1;
			$this->resp['data'] = $data;
		}
	}
	
	/**
	 * 编辑
	 */
	public function edit(): void
	{
		$id     = $this->post('id') ?: self::getId();
		$action = $this->post('action') ?: '已入库';
		
		$detail           = !empty($_POST['detail']) ? json_decode($_POST['detail'], true) : [];
		$mxIdArr          = $this->post('mxId') ?: inStockClass::getJsonValue('id', $detail);
		$materialSkuIdArr = $this->post('materialSkuId') ?: inStockClass::getJsonValue('materialSkuId', $detail);
		$unitArr          = $this->post('unit') ?: inStockClass::getJsonValue('unit', $detail);
		$numArr           = $this->post('num') ?: inStockClass::getJsonValue('num', $detail);
		$priceArr         = $this->post('price') ?: inStockClass::getJsonValue('price', $detail);
		$mxTextArr        = $this->post('mxText') ?: inStockClass::getJsonValue('mxText', $detail);
		$batchArr         = $this->post('batch') ?: inStockClass::getJsonValue('batch', $detail);
		$warehouseArr     = $this->post('warehouseId') ?: inStockClass::getJsonValue('warehouseId', $detail);
		$objDate          = ($action == '已出库') ? 'recordDate' : 'orderDate';
		$field            = [
			// 'warehouseId' => $this->post('waid'),
			'targetId' => $this->post('targetId'),
			$objDate   => $this->post('orderDate'),
			'type'     => $this->post('type'),
			'text'     => $this->post('text'),
		];
		$annotation       = [
			// 'warehouseId' => '仓库',
			'targetId' => '客户',
			$objDate   => '单据日期',
			'type'     => '单据类型',
			'text'     => '备注',
		];
		$rules            = [
			// 'warehouseId' => 'required',
			'targetId' => 'required',
			'type'     => 'required',
			$objDate   => 'required|date',
			// 'text'           => 'required',
		];
		// 校验是否符合规则
		$vt     = new verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$this->resp['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
			goto resp;
		}
		$where = " coid = '" . self::$coid . "' AND id = '$id' ";
		$info  = query(inStockClass::tableMap($action)['table'], $where);
		//判断
		if (!$this->power(self::page, "edit")) {
			$this->resp['warn'] = "你没有编辑" . self::title . "的权限";
		} elseif (self::is_null_array($mxIdArr)) {
			$this->resp['warn'] = '请选择出库明细';
		} elseif (self::is_null_array($materialSkuIdArr)) {
			$this->resp['warn'] = '请选择出库明细';
		} elseif (self::is_null_array($numArr)) {
			$this->resp['warn'] = '数量请填写完整';
		} elseif (self::is_null_array($priceArr)) {
			$this->resp['warn'] = '价格请填写完整';
		} elseif (self::is_null_array($unitArr)) {
			$this->resp['warn'] = '请选择主单位';
		} elseif (self::is_null_array($warehouseArr)) {
			$this->resp['warn'] = '请选择出库仓库';
		} elseif (!empty($info['id']) && $info['state'] == '已出库') {
			$this->resp['warn'] = '此出库单已出库，不能修改';
		} else {
			$this->startTrans();
			$isPass = true;//事务通过标志
			if (!$info['id']) {
				$orderNo            = codeTemplateClass::generateCode(self::page, [
					'prefix' => 'CKD' . date('Ymd'),
					'table'  => inStockClass::tableMap($action)['table'],
					'field'  => 'orderNo',
					'where'  => " AND coid = '" . self::$coid . "' ",
				], $field);
				$field              = array_merge($field, [
					'id'       => $id,
					'orderNo'  => $orderNo,
					'classify' => 0,
					'state'    => '待出库',
					'coid'     => self::$coid,
					'stid'     => $this->control['stid'],
				]);
				$this->resp['warn'] = static::insert([
					"table" => inStockClass::tableMap($action)['table'],
					"field" => $field,
				]);
			} else {
				$this->resp['warn'] = static::update([
					"table" => inStockClass::tableMap($action)['table'],
					"field" => $field,
					"where" => $where,
				]);
			}
			//添加或更新报价单明细
			if (is_array($mxIdArr)) {
				foreach ($mxIdArr as $k => $nid) {
					$mx          = query(inStockClass::tableMap($action)['tableMx'], "id = '$nid'");
					$materialSku = query('material_sku', "id = '$materialSkuIdArr[$k]'");
					if (!empty($mx['id'])) {
						//更新
						$warn = static::update([
							"table" => inStockClass::tableMap($action)['tableMx'],
							"field" => [
								'materialId'    => $materialSku['materialId'],
								'materialSkuId' => $materialSkuIdArr[$k] ?: '',
								'num'           => $numArr[$k] ?: 0,
								'orderNum'      => $numArr[$k] ?: 0,
								'price'         => $priceArr[$k] ?: 0,
								'unit'          => $unitArr[$k] ?: '',
								'warehouseId'   => $warehouseArr[$k] ?: '',
								'batch'         => $batchArr[$k] ?: '',
								'money'         => static::formattingFigure($numArr[$k] * $priceArr[$k]),
								'text'          => $mxTextArr[$k] ?: '',
							],
							"where" => " id = '$nid'",
						]);
					} else {
						//新增
						$warn = static::insert([
							"table" => inStockClass::tableMap($action)['tableMx'],
							"field" => [
								'id'            => $nid,
								'coid'          => self::$coid,
								'orderId'       => $id,
								'materialId'    => $materialSku['materialId'],
								'materialSkuId' => $materialSkuIdArr[$k],
								'num'           => $numArr[$k],
								'orderNum'      => $numArr[$k] ?: 0,
								'price'         => $priceArr[$k],
								'unit'          => $unitArr[$k],
								'warehouseId'   => $warehouseArr[$k],
								'batch'         => $batchArr[$k] ?: '',
								'money'         => static::formattingFigure($numArr[$k] * $priceArr[$k]),
								'text'          => $mxTextArr[$k],
							],
						]);
					}
					if (!in_array($warn, ['新增成功', '更新成功'])) {
						$isPass             = false;
						$this->resp['warn'] = $warn;
						break;
					}
				}
			}
			if (in_array($this->resp['warn'], ["新增成功", "更新成功"]) && $isPass) {
				$this->commitTrans();
				delete(['table' => inStockClass::tableMap($action)['tableMx'], 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"]);
				//添加日志
				$type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$this->code         = 1;
				$this->resp['data'] = $id;
			} else {
				$this->rollback();
			}
		}
		
		resp:
	}
	
	
	/**
	 * 部分出库
	 */
	public function putOut()
	{
		$id     = $this->post('id');
		$num    = $this->post('num');
		$batch  = $this->post('batch');
		$action = $this->post('action') ?: '已出库';
		$info   = query(inStockClass::tableMap($action)['tableMx'], " id = '$id'");
		$res    = query(inStockClass::tableMap($action)['table'], " id = '$info[orderId]' ");
		if (!$this->power(self::page, 'edit')) {
			$this->resp['warn'] = '你还没有出库权限';
		} elseif (empty($res['id']) || empty($info['id'])) {
			$this->resp['warn'] = '未找到此出库单';
		} elseif (static::isNull($num)) {
			$this->resp['warn'] = '请填写数量';
		} elseif (!in_array($res['state'], ['待出库', '部分出库'])) {
			$this->resp['warn'] = '此出库单不是出库状态，不能出库';
		} elseif (abs($num) + $info['num'] > $info['orderNum']) {
			$this->resp['warn'] = '出库数量不能超过单据数量，你还可以出库' . ($info['orderNum'] - $info['num']);
		} else {
			$num = abs($num);
			$this->startTrans();
			$isPass             = false; // 事务通过标志
			$detailMoney        = ($info['num'] + $num) * $info['price'] * (1 + $info['rate']);
			$this->resp['warn'] = static::update([
				"table" => inStockClass::tableMap($action)['tableMx'],
				"field" => [
					'batch' => $batch,
					'num'   => $info['num'] + $num,
					'money' => $detailMoney,
				],
				"where" => "id = '$info[id]'",
			]);
			if (!in_array($this->resp['warn'], ["新增成功", "更新成功"])) {
				//回滚
				$this->rollback();
			} else {
				$isPass = true;
				if ($res['state'] == '待出库') {
					static::update([
						'table' => inStockClass::tableMap($action)['table'],
						'field' => [
							'state'      => '部分出库',
							'commitTime' => $this->time,
						],
						'where' => " id = '{$res['id']}' ",
					]);
				}
				if ($isPass === true) {
					$mainUnitNum = inventoryBalanceClass::toMainUnit($info['materialSkuId'], $num, $info['unit']);
					// 判断库存
					if (inventoryBalanceClass::inventoryNum($info['materialSkuId'], $info['warehouseId']) - $mainUnitNum < 0) {
						$this->resp['warn'] = '出库数量不能大于库存数量';
						return;
					}
					insert([
						'table' => self::tableRecord,
						'field' => [
							'id'            => self::getNo(),
							'coid'          => self::$coid,
							'warehouseId'   => $info['warehouseId'],
							'materialId'    => $info['materialId'],
							'materialSkuId' => $info['materialSkuId'],
							// 'inventoryId'   => $info['orderId'],
							// 'inventoryMxId' => $info['id'],
							'num'           => -1 * $mainUnitNum,
							'changesId'     => $info['id'],
						],
					]);
					$material = query('material', " id = '$info[materialId]' ", 'code, name, brand, model, unit');
					auditingFollow([
						"type"   => "出库单",
						"typeId" => self::generateId([$info['orderId'], $info['materialSkuId']]),
						"text"   => "【{$this->control['name']}】通过【前端】出库【{$material['name']}-{$material['brand']}-{$material['model']}】数量[$num]",
					]);
					$this->commitTrans();//提交事务
				}
				//添加日志
				$type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				$this->resp['data'] = $res['id'];
				$this->code         = 1;
			}
		}
		resp:
	}
	
	
	/**
	 * 确认出库
	 */
	public function done()
	{
		$id     = $this->post('id');
		$action = $this->post('action') ?: '已出库';
		$info   = query(inStockClass::tableMap($action)['table'], " coid = '" . static::$coid . "' AND id = '$id'");
		// 库存是否需要复核
		$checkCtrl = optionSettingClass::getSettingItem('库存', 'checkCtrl');
		if ($checkCtrl) {
			$field = [
				'state'       => '已出库',
				'confirmTime' => $this->time,
			];
		} else {
			$field = [
				'state'       => '已复核',
				'confirmTime' => $this->time,
				'reviewTime'  => $this->time,
			];
		}
		if (!$this->power(static::page, 'edit')) {
			$this->resp['warn'] = L('outStockExec.confirmEdit.power');
		} elseif (empty($info['id'])) {
			$this->resp['warn'] = L('outStockExec.confirmEdit.empty');
		} elseif (!in_array($info['state'], ['待出库', '部分出库'])) {
			$this->resp['warn'] = L('outStockExec.confirmEdit.stateError');
		} else {
			$this->startTrans();
			$isPass = true; // 事务通过标志
			
			$this->resp['warn'] = static::update([
				"table" => inStockClass::tableMap($action)['table'],
				"field" => $field,
				"where" => "id = '$info[id]'",
			]);
			if (in_array($this->resp['warn'], ["新增成功", "更新成功"]) && $isPass === true) {
				$details = find([
					'table' => inStockClass::tableMap($action)['tableMx'],
					'where' => " orderId = '{$info['id']}'",
				]);
				/***仓库允许零库存出库*/
				$outAllowZero = optionSettingClass::getSettingItem('库存', 'outAllowZero');
				foreach ($details['array'] as $key => $value) {
					// 转换主单位
					$mainUnitNum = inventoryBalanceClass::toMainUnit($value['materialSkuId'], $value['num'], $value['unit']);
					$stock       = inventoryBalanceClass::inventoryNum($value['materialSkuId'], $value['warehouseId'], false, $value['batch']);
					// 判断库存
					if (!$outAllowZero && $stock - $mainUnitNum < 0) {
						$this->resp['warn'] = L('outStockExec.confirmEdit.transfinite');
						goto resp;
					} elseif ($outAllowZero && $stock - $mainUnitNum < 0) {
						$material     = query("material", " id = '" . $value['materialId'] . "' ", "name");
						$material_sku = query("material_sku", " id = '" . $value['materialSkuId'] . "' ", "name");
						//发送负库存预警
						$setting = static::getSettingValue('inventoryNegative');
						foreach ($setting['member'] as $item) {
							message(array(
								"stid"      => $item,
								"type"      => '预警消息',
								"typeId"    => $value['materialSkuId'],
								"text"      => "物料【" . $material['name'] . "-" . $material_sku['name'] . "】负库存预警",
								"targetCla" => 'inventoryBalance',
								"targetFun" => 'detail',
							));
						}
					}
					$bool = inventoryBalanceClass::inventoryControl($value['materialId'], $mainUnitNum);  //最低库存控制
					if ($bool !== true) {
						$this->resp['warn'] = $bool;
						goto resp;
					}
					$inventory_detail = ['orderId' => '', 'id' => ''];
					if ($value['sourceId']) {
						$inventory_detail = query("inventory_detail", " id = '$value[sourceId]' ");
						$inventory        = query("inventory", " id = '$inventory_detail[orderId]' ");
						// 累计金额
						$detailMoney        = ($inventory_detail['num'] + $value['num']) * $inventory_detail['price'] * (1 + $inventory_detail['rate']);
						$nowNum             = $inventory_detail['num'] + $value['num'];
						$this->resp['warn'] = static::update([
							"table" => 'inventory_detail',
							"field" => [
								'num'   => $nowNum,
								'money' => $detailMoney,
							],
							"where" => "id = '$inventory_detail[id]'",
						]);
						if (!in_array($this->resp['warn'], ["新增成功", "更新成功"])) {
							goto resp;
						}
						//如果是配料出库，则生成线边库存记录
						if ($inventory['type'] == '配料出库') {
							$bool = tempInventoryClass::insertRecord(array(
								'lineId'        => $inventory['targetId'],
								'materialId'    => $inventory_detail['materialId'],
								'materialSkuId' => $inventory_detail['materialSkuId'],
								'inventoryId'   => $inventory['id'],
								'inventoryMxId' => $inventory_detail['id'],
								'num'           => -1 * $mainUnitNum,
								'batch'         => $value['batch'],
								'changesId'     => $value['id'],
							));
							if ($bool !== true) {
								$this->resp['warn'] = $bool;
								goto resp;
							}
						}
						
						//如果是生产领料且未关联生产计划单，也生成线边库存记录
						if ($inventory['type'] == '生产领料') {
							$pick_order_detail = query('pick_order_detail', "id = '$inventory_detail[sourceId]'");
							if (!empty($pick_order_detail['id']) && empty($pick_order_detail['sourceId'])) {
								$bool = tempInventoryClass::insertRecord(array(
									'lineId'        => $inventory['targetId'],
									'materialId'    => $inventory_detail['materialId'],
									'materialSkuId' => $inventory_detail['materialSkuId'],
									'inventoryId'   => $inventory['id'],
									'inventoryMxId' => $inventory_detail['id'],
									'num'           => -1 * $mainUnitNum,
									'batch'         => $value['batch'],
									'changesId'     => $value['id'],
								));
								if ($bool !== true) {
									$this->resp['warn'] = $bool;
									goto resp;
								}
							}
						}
						
						// 关联表
						$targetDate = $targetNo = $targetText = $hiddenText = ' ';
						if ($inventory['sourceTable']) {
							$obj = query($inventory['sourceTable'], " id = '{$inventory['sourceId']}' ");
							if (!empty($obj['id'])) {
								$targetDate = $obj['recordDate'];
								$targetNo   = $obj['orderNo'];
								$targetText = $inventory['type'] . "单【{$obj['orderNo']}】";
								$hiddenText = $inventory['type'] . '单ID：' . $obj['id'] . '，出库单ID：' . $inventory_detail['orderId'] . '出库单子ID：' . $inventory_detail['id'];
							}
						}
						$bool = supplierClass::insertRecord($inventory['targetId'], $inventory['type'], round($value['num'] * $inventory_detail['price'] * (1 + $inventory_detail['rate']), 2), 'inventory_detail', $inventory_detail['id'], $targetDate, $targetNo, $targetText, $hiddenText, $value['id']);
						if ($bool !== true) {
							$this->resp['warn'] = $bool;
							goto resp;
						}
						//修改待出库单状态
						$notOut = find(array('table' => 'inventory_detail', 'single' => "orderId = '$inventory[id]' and num < orderNum and coid = '" . static::$coid . "' and id <> '" . $inventory_detail['id'] . "'", 'field' => " IFNULL(count(id),0) as num "));
						if ($nowNum >= $inventory_detail['orderNum'] && $notOut['num'] == 0) {
							static::update([
								'table' => 'inventory',
								'field' => [
									'state'       => '已出库',
									'confirmTime' => $this->time,
								],
								'where' => " id = '{$inventory['id']}' ",
							]);
						} elseif ($inventory['state'] == '待出库') {
							static::update([
								'table' => 'inventory',
								'field' => [
									'state'      => '部分出库',
									'commitTime' => $this->time,
								],
								'where' => " id = '{$inventory['id']}' ",
							]);
						}
					}
					//查询从早到晚的所有仓位和批次剩余的库存，依次出库
					$fieldArr = static::resolveField([
						'field' => '`id`, `coid`, `positionId`,`batch`, `materialId`, `materialSkuId`, SUM(num) as num, `time`',
						'group' => 'positionId',
					]);
					//查询结果
					$where  = " coid = '" . static::$coid . "' and materialSkuId = '$value[materialSkuId]' and warehouseId = '" . $value['warehouseId'] . "' and batch = '" . $value['batch'] . "' ";
					$where  .= $fieldArr['group'];
					$result = find(array('table' => 'inventory_record', 'field' => $fieldArr['field'], 'where' => $where . " order by num desc "));
					foreach ((array)$result['array'] as $k => $array) {
						if ($mainUnitNum > 0) {
							if ($mainUnitNum > $array['num']) {
								$now = ($k == (count($result['array']) - 1)) || $array['num'] <= 0 ? $mainUnitNum : $array['num'];
							} else {
								$now = $mainUnitNum;
							}
							$mainUnitNum -= $now;
							insert([
								'table' => static::tableRecord,
								'field' => [
									'id'            => static::getNo(),
									'coid'          => static::$coid,
									'warehouseId'   => $value['warehouseId'],
									'positionId'    => $array['positionId'],
									'materialId'    => $value['materialId'],
									'materialSkuId' => $value['materialSkuId'],
									'batch'         => $value['batch'],
									'num'           => -1 * $now,
									'inventoryId'   => $inventory_detail['orderId'],
									'inventoryMxId' => $inventory_detail['id'],
									'changesId'     => $value['id'],
								],
							]);
							if (!empty($array['positionId'])) {
								inventoryBalanceClass::recordStockToLocation('', ['materialSkuId' => $value['materialSkuId'], 'warehouseId' => $value['warehouseId'], 'positionId' => $array['positionId'], 'batch' => $value['batch']]);
							}
						}
					}
					if ($mainUnitNum > 0) {
						$positionId = inventoryBalanceClass::matchLocation($value['warehouseId']);
						insert([
							'table' => static::tableRecord,
							'field' => [
								'id'            => static::getNo(),
								'coid'          => static::$coid,
								'warehouseId'   => $value['warehouseId'],
								'positionId'    => $positionId,
								'materialId'    => $value['materialId'],
								'materialSkuId' => $value['materialSkuId'],
								'batch'         => $value['batch'],
								'num'           => -1 * $mainUnitNum,
								'inventoryId'   => $inventory_detail['orderId'],
								'inventoryMxId' => $inventory_detail['id'],
								'changesId'     => $value['id'],
							],
						]);
						if (!empty($positionId)) {
							inventoryBalanceClass::recordStockToLocation('', ['materialSkuId' => $value['materialSkuId'], 'warehouseId' => $value['warehouseId'], 'positionId' => $positionId, 'batch' => $value['batch']]);
						}
					}
				}
				$this->commitTrans();//提交事务
				auditingFollow(array(
					"type"   => "出库单",
					"typeId" => $info['id'],
					"text"   => "【{$this->control['name']}】确认",
				));
				//添加日志
				$type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
				$text = str_replace(['{{staffName}}', '{{type}}', '{{id}}'], [$this->control['name'], $type, $id], lang('outStockExec.confirmEdit.log'));
				$this->logText(["type" => static::page, "text" => $text]);
				$this->code = 1;
			}
		}
		
		resp:
	}
	
	
	/**
	 * 复核
	 */
	public function check()
	{
		$id     = $this->post('id');
		$action = $this->post('action') ?: '已出库';
		$info   = query(inStockClass::tableMap($action)['table'], " coid = '" . self::$coid . "' AND id = '$id'");
		$field  = [
			'state'      => '已复核',
			'reviewTime' => $this->time,
		];
		if (!$this->power(self::page, 'check')) {
			$this->resp['warn'] = L('outStockExec.checkEdit.power');
		} elseif (empty($info['id'])) {
			$this->resp['warn'] = L('outStockExec.checkEdit.empty');
		} elseif ($info['state'] != '已出库') {
			$this->resp['warn'] = L('outStockExec.checkEdit.statusError');
		} else {
			$this->resp['warn'] = static::update([
				"table" => inStockClass::tableMap($action)['table'],
				"field" => $field,
				"where" => "id = '$info[id]'",
			]);
			if (in_array($this->resp['warn'], ["新增成功", "更新成功"])) {
				auditingFollow([
					"type"   => "出库单",
					"typeId" => $info['id'],
					"text"   => "【{$this->control['name']}】复核",
				]);
				//添加日志
				$type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
				$text = str_replace(['{{staffName}}', '{{type}}', '{{id}}'], [$this->control['name'], $type, $id], lang('outStockExec.checkEdit.log'));
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$this->code = 1;
			}
		}
	}
}
